/**
 * admin_info 房间路由模块
 */
const express = require('express');
const router = express.Router();
const ResultJson = require('../model/ResultJson.js');
const ServiceFactory = require('../factory/ServiceFactory.js');
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const jwt = require('jsonwebtoken');
const AppConfig = require('../config/Appconfig.js');
const uplaod = multer({
  dest: path.join(__dirname, '../adminPhoto')
});

router.get('/getAdminListByName', async (req, res) => {
  let results = await ServiceFactory.adminInfoService.getAdminListByName(req.query);
  res.json(new ResultJson(true, '数据请求成功', results));
});

router.post('/add', async (req, resp) => {
  let results = await ServiceFactory.adminInfoService.add(req.body);
  resp.json(new ResultJson(results, results ? '新增成功' : '新增失败'));
});

router.get('/deleteById', async (req, res) => {
  let { id } = req.query;
  let results = await ServiceFactory.adminInfoService.deleteById(id);
  res.json(new ResultJson(results, results ? '删除成功' : '删除失败'));
});

router.post('/uploadAdminPhoto', uplaod.single('admin_photo'), async (req, res) => {
  let file = req.file;
  if (file) {
    fs.renameSync(file.path, file.path + file.originalname);
    res.json(
      new ResultJson(true, '文件上传成功', `/adminPhoto/${file.filename + file.originalname}`)
    );
  } else {
    res.status(404).json(new ResultJson(false, '没有接收到文件'));
  }
});

router.post('/checkLogin', async (req, resp) => {
  let results = await ServiceFactory.adminInfoService.checkLogin(req.body);
  if (results) {
    //登陆成功
    let token = jwt.sign(
      {
        adminInfo: results
      },
      AppConfig.jwtKey,
      {
        expiresIn: 60 * 30
      }
    );
    resp.json(new ResultJson(true, '登陆成功', token));
  } else {
    //登陆失败
    resp.json(new ResultJson(false, '登陆失败,账号或密码不正确'));
  }
});

module.exports = router;
